// pages/diandan/diandan.js
import { async } from '../../lib/runtime/runtime.js';
import {request} from '../../request/index.js'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    uid:0,
    activeKey: 0,
    value: '',
    pages:"",
    sid:0,//商家id
    cid:0,//侧边栏id
    CategoryList:[],
    CategoryGoodsList:[],
    show: false,
    stop_id:0, //商品id
    blurbList:[],
    values:[],
    arr: [],
    indexArr: [],
    num:1,
    //是否收藏
    shoucang:'icon-xingxing',
    //查询收藏用户名字
    CollectsGood:[],
    //添加收藏
    Add: [],
    //查询name+openid
    CollectsGoods:[]

  },
  async  getCollectsGood(id){

    const result =  await request({
      url:  "/Collects/Collects_goods",
      data:{
        id : id
      }
    }) 
    console.log(result);

    this.setData({
      CollectsGood : result.data.list
    })
    //当前用户收藏的数据
    let {CollectsGood} = this.data;
    //当前页面内容name
    let {blurbList} = this.data;
        var blname=blurbList.name;

    

  },
  //查询删除
  async  getCollectsDelete(name){

    const result =  await request({
      
      url:  "/Collects/Collects_delete",
      data:{
        name : name,
      }
    }) 

  },
  async  getAdd(userid,name,description,mainimg,price,sum,status,storeId){

    const result =  await request({
      url:  "/Collects/add",
    
      data:{
        userid : userid,
        name :name,
        description:description,
        mainImg:mainimg,
        price:price,
        sum:sum,
        status:status,
        storeId:storeId,
      }
    }) 
    console.log(result);

    // this.setData({
    //   Add : result.data.list
    // })

  },
  shoucang(){
    var Info=wx.getStorageSync('userInfo');
     //获取名字
     var Infos=Info.id;
     console.log();
      //判断名字是否为空
      if(Info == ''){
        wx.showModal({
          title: '提示',
          content: '用户未登录',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              wx.navigateTo({
                url: '/pages/loginbutton/index',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }else{

        this.getCollectsGood(Infos);
        
        if(this.data.shoucang==='icon-xingxing'){
          
          this.setData({
            
            shoucang:'icon-xingxing1',
          })
          // wx.setStorageSync("blurbList",blurbList);

          //添加收藏
          console.log(Infos);
          var name=this.data.blurbList.name;
          var description=this.data.blurbList.description;
          var mainimg=this.data.blurbList.mainimg;
          var price=this.data.blurbList.price;
          var sum=this.data.blurbList.sum;
          var status=this.data.blurbList.status;
          var storeId=this.data.blurbList.storeId;
          this.getAdd(Infos,name,description,mainimg,price,sum,status,storeId);
        }else{
          this.setData({
            shoucang:'icon-xingxing'
          })
          //删除
          var name=this.data.blurbList.name;
          this.getCollectsDelete(name);
          wx.showModal({
            title: '提示',
            content: '取消收藏',
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }

  },
  exchangeStore(){
    wx.switchTab({
      url: '/pages/theStore/index'
      });
  },
  onChange(e) {
    this.setData({
      value: e.detail,
    });
  },
  //点击选规格
  showPopup(e) {
      
  var  _this = this;
    console.log(e.target.dataset.index);
    this.setData({
       show: true ,
       stop_id :e.target.dataset.index,
       num:1
      });
      this.getDityList()
  },
  //获取详情
  async getDityList(){
    const result =  await request({
      url: '/CategoryGoods/categoryGoodsID',
      data:{
        id : this.data.stop_id
      }
    }) 
    //查询id
    console.log(result.data.CategoryGoods);
    //需要在这里判断收藏
    // console.log("查询name"+result.data.CategoryGoods.name);
    var Info=wx.getStorageSync('userInfo');
     //获取用户id
     var Infos=Info.id;
     console.log(Infos);
         //当前用户收藏的数据
    let {CollectsGood} = this.data;
    console.log(CollectsGood);
    //当前页面内容name
    var blname=result.data.CategoryGoods.name;
    console.log(blname);
    //数组长度不能为空
    if(Info!=''){
      //判断收藏图标
      for(var i=0;i<CollectsGood.length;i++){
        if(CollectsGood[i].name===blname){
          console.log(CollectsGood[i].name);
          this.setData({
            shoucang:'icon-xingxing1',
          })

          wx.getStorageSync('shoucang','icon-xingxing1');
          break;
        }else{
          this.setData({
            shoucang:'icon-xingxing',
          })
          wx.getStorageSync('shoucang','icon-xingxing');
        }
      } 
    }else{
    
      console.log("用户未登录，不显示是否收藏");
    }

    this.setData({
      blurbList : result.data.CategoryGoods,
      values: result.data.CategoryGoods.values,
    })
    console.log(this.data.values);
    const res = this.data.indexArr;
    const resArr = this.data.arr;

    this.data.values.forEach((e,i) => {
      res[i] = 0;
      resArr[i]= e.value[0];
      this.setData({
       indexArr: res,
       arr:resArr
      })
     });
  }  
  ,

  onClose() {
    this.setData({ 
      show: false ,

    });
  },
  //规格选择
  choice(e){
    console.log(e.currentTarget.dataset.fid);
    const fid = e.currentTarget.dataset.fid;
    const id = e.currentTarget.dataset.id;

   const arr = this.data.arr,
   arr2 = this.data.indexArr;

    arr[fid] = this.data.values[fid].value[id];
   arr2[fid] = id;
   
   this.setData({
    arr: arr,
    indexArr: arr2
   })
  },
 async getAddress(){
    const result =  await request({
      url: '/sites/Sites_id',
      data:{
        user_id : this.data.uid
      }
    })
    console.log(result);
    const length = result.data.list.length;
      if(length!=0){
        wx.navigateTo({
          url: '/pages/addList/list',
        })
        
      }else{
        wx.navigateTo({
          url: '/pages/addAddress/addAddress',
        })
      }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    console.log(e.sid);
    let userinfo =wx.getStorageSync('userInfo')
    let uid =userinfo.id
    this.setData({
      sid :e.sid,
      uid:uid
    })
    this.getCategoryList();

  
    
  
  },

 async  getCategoryList(){
    const result =  await request({
      url: '/Category/CategoryList',
      data:{
        sid: this.data.sid
      }
    }) 
    //"侧边栏数据"+
    console.log("侧边栏数据");
    console.log(result.data.CategoryGoods);
    
    this.setData({
      CategoryList : result.data.CategoryGoods,
      cid : result.data.CategoryGoods[0].id
    })

    this.getCategoryGoodsById(this.data.cid);
    
  },
  // 侧边栏点击事件
 async checkedSub(event) {
  this.setData({
    activeKey:event.detail
   })
  
    if(event.currentTarget.dataset.name == "新品尝鲜"){
    
        this.categoryGoodsList();
    }else{
      this.getCategoryGoodsById(event.currentTarget.dataset.index);

    }

  },

async  getCategoryGoodsById(cid){

    const result =  await request({
      url:  "/CategoryGoods/categoryGoodsListID",
      data:{
        cid :cid
      }
    }) 
   

    this.setData({
      CategoryGoodsList : result.data.Category
    })

  },


  async categoryGoodsList(){
      const result =  await request({
        url:  "/CategoryGoods/categoryGoodsList",
        data:{
          storeId : this.data.sid
        }
        
      })
      console.log(result.data.Category); 
     
      this.setData({
        CategoryGoodsList : result.data.Category
      })
   
    },

    //点击加入购物袋事件
  async  goTocart(){
      const {arr,num} = this.data;
      var Info=wx.getStorageSync('userInfo');

      //获取id
      var uid=Info.id;
      const   {stop_id}=   this.data ;
   
      const result =  await request({
       
        url: '/shopping_cart/addCart',
        data:{
        user_id : uid,
        dish_id :stop_id,
        number:num,
        dish_flavor:arr   
        }
      }) 
     console.log(result);

   

      wx.navigateTo({
        url:'/pages/shopping/shopping'
    })
    },
    /* 点击减号 */
    bindMinus: function() { 
     
      var num = this.data.num; 
      // 如果大于1时，才可以减 
      if (num > 1) { 
        num --; 
      }else{
        Toast("单笔订单最少需要买一件")
      }
      
      // 只有大于一件的时候，才能normal状态，否则disable状态 
  
      // 将数值与状态写回 
      this.setData({ 
        num: num, 
      }); 
    }, 
    /* 点击加号 */
    bindPlus: function() { 
      var num = this.data.num; 
      // 不作过多考虑自增1 
      if(num<49){
        num ++; 
      }else{
        Toast("单笔订单最少需要买49件")
      }
      // 只有大于一件的时候，才能normal状态，否则disable状态 
   
      // 将数值与状态写回 
      this.setData({ 
        num: num, 

      }); 
    }, 
    /* 输入框事件 */
    bindManual: function(e) { 
      var num = e.detail.value; 
      // 将数值与状态写回 
      this.setData({ 
        num: num 
      }); 
    } ,
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var Info=wx.getStorageSync('userInfo');
      //获取名字
      var Infos=Info.id;

    //绑定用户,获取到当前用户收藏的所有数据
    this.getCollectsGood(Infos);

  },
  async getstorepage(){
    const result =  await request({
      url: '/store/store_page'
    }) 
    console.log(result.data.list);
    this.setData({
      storepage :result.data.list
    })
    this.getDistance()

  
   }

})